//
//  NSPhotoImageCell.m
//  Meboo
//
//  Created by kyo on 2024/4/18.
//

#import "NSPhotoImageCell.h"
#import "GXPHKitTool.h"
#import <AFHTTPSessionManager.h>
@interface NSPhotoImageCell()

@end

@implementation NSPhotoImageCell
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

#pragma mark - Public Metohd
- (void)setAssetModel:(GXPhotoAssetModel *)assetModel {
    _assetModel = assetModel;
    CGSize imgSize = self.contentView.bounds.size;
    PHImageRequestOptions * options = [[PHImageRequestOptions alloc]init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    [[GXPHKitTool sharedPHKitTool].phManager requestImageForAsset:assetModel.asset
                                                       targetSize:imgSize
                                                      contentMode:PHImageContentModeAspectFill
                                                          options:options
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        self.photoImageView.image = result;
        if (assetModel.asset.mediaType == PHAssetMediaTypeVideo) {
            //视频显示时间
            self.timeLabel.hidden = NO;
            [self setTimeStr:assetModel.asset.duration];
        } else {
            self.timeLabel.hidden = YES;
        }
    }];
    
    if (assetModel.asset.mediaType == PHAssetMediaTypeVideo) {
        __WeakSelf
        [[PHImageManager defaultManager] requestAVAssetForVideo:assetModel.asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *asset0 = (AVURLAsset *)asset;
             weakSelf.videoUrl = asset0.URL;
        }];
    }
}

- (void)setPrivateModel:(NSPrivatePhotoModel *)privateModel {
    _privateModel = privateModel;
    if (privateModel.videoLength.length > 0) {
        if ([[SDImageCache sharedImageCache] imageFromDiskCacheForKey:privateModel.imageUrl]) {
            self.photoImageView.image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:privateModel.imageUrl];
        } else {
            [self getVideoFirstViewImage:privateModel.imageUrl];
        }
        //视频显示时间
        self.timeLabel.hidden = NO;
        [self setTimeStr:[privateModel.videoLength integerValue]];
//        self.videoUrl = [NSURL URLWithString:privateModel.imageUrl];
//        [self playerDownload:privateModel.imageUrl];
    } else {
        [self.photoImageView sd_setImageWithURL:[NSURL URLWithString:privateModel.imageUrl]];
        self.timeLabel.hidden = YES;
    }
}

// 获取视频第一帧
- (void)getVideoFirstViewImage:(NSString *)videoURL{
    __WeakSelf
    NSString *url = [NSString stringWithFormat:@"%@?flag=2",videoURL];
    __block UIImage *videoImage;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:url] options:nil];
        NSParameterAssert(asset);
        AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
        assetImageGenerator.appliesPreferredTrackTransform = YES;
        assetImageGenerator.apertureMode =AVAssetImageGeneratorApertureModeEncodedPixels;
        CGImageRef thumbnailImageRef = NULL;
        NSError *thumbnailImageGenerationError = nil;
        thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(0, 60)actualTime:NULL error:&thumbnailImageGenerationError];
        if(!thumbnailImageRef)
            NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
        videoImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef]: nil;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //主线程更新UI
            weakSelf.photoImageView.image = videoImage;
            //缓存图片
            [[SDImageCache sharedImageCache] storeImage:videoImage forKey:videoURL toDisk:YES completion:^{
                
            }];
        });
        
    });
}

//-----下载视频--
- (void)playerDownload:(NSString *)url{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.videoPath = [defaults objectForKey:url];
    if (self.videoPath.length > 0) {
        return;
    }
    __WeakSelf
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy-MM-ddHH:mm:ss";
    NSString *dateStr = [format stringFromDate:[NSDate date]];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,[NSString stringWithFormat:@"%@.mp4",dateStr]];
    NSLog(@"fullPath = %@",fullPath);
    NSURL *urlNew = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlNew];
    NSURLSessionDownloadTask *task =
    [manager downloadTaskWithRequest:request
                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                return [NSURL fileURLWithPath:fullPath];
                            }
                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                       NSLog(@"%@",response);
        weakSelf.videoPath = fullPath;
        [defaults setObject:fullPath forKey:url];
        [defaults synchronize];
                   }];
    [task resume];
}

#pragma mark - Action
- (void)setTimeStr:(NSInteger)duration {
    if (duration < 60) {
        NSString *sec = [NSString stringWithFormat:@"%ld",duration];
        if (sec.length == 1) {
            sec = [NSString stringWithFormat:@"0%@",sec];
        }
        self.timeLabel.text = [NSString stringWithFormat:@"0:%@",sec];
    } else if (duration < 3600) {
        NSString *sec = [NSString stringWithFormat:@"%ld",duration%60];
        if (sec.length == 1) {
            sec = [NSString stringWithFormat:@"0%@",sec];
        }
        self.timeLabel.text = [NSString stringWithFormat:@"%ld:%@",duration/60,sec];
    } else{
        NSString *min = [NSString stringWithFormat:@"%ld",duration%3600/60];
        if (min.length == 1) {
            min = [NSString stringWithFormat:@"0%@",min];
        }
        
        NSString *sec = [NSString stringWithFormat:@"%ld",duration%3600%60];
        if (sec.length == 0) {
            sec = [NSString stringWithFormat:@"0%@",sec];
        }
        self.timeLabel.text = [NSString stringWithFormat:@"%ld:%@:%@",duration/3600,min,sec];
    }
}

#pragma mark - UI
- (void)setupUI {
    self.contentView.backgroundColor = UIColor.clearColor;
    self.contentView.layer.cornerRadius = MBHeightScale(4);
    
    [self.contentView addSubview:self.photoImageView];
    [self.photoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
    
    [self.contentView addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(MBWidthScale(-5));
        make.top.mas_equalTo(MBWidthScale(4));
    }];
}

#pragma mark - Setter && Getter
- (UIImageView *)photoImageView {
    if (!_photoImageView) {
        _photoImageView = [UIImageView new];
        _photoImageView.contentMode = UIViewContentModeScaleAspectFill;
        _photoImageView.layer.cornerRadius = MBHeightScale(4);
        _photoImageView.layer.masksToBounds = YES;
        [_photoImageView setClipsToBounds:YES];
    }
    return _photoImageView;
}


- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [UILabel new];
        _timeLabel.hidden = YES;
        _timeLabel.font = MBHelFontSizeScale(12);
        _timeLabel.textColor = HEXS(@"ffffff");
    }
    return _timeLabel;
}
@end
